###############################################################################
# SuperLinks                                                                  #
# Copyright (c) 2000-2007 Greg Nolle (http://greg.nolle.co.uk)                #
###############################################################################
# This program is free software; you can redistribute it and/or modify it     #
# under the terms of the GNU General Public License as published by the Free  #
# Software Foundation; either version 2 of the License, or (at your option)   #
# any later version.                                                          #
#                                                                             #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for   #
# more details.                                                               ##                                                                             #
# You should have received a copy of the GNU General Public License along     #
# with this program; if not, write to the Free Software Foundation, Inc.,     #
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                 #
###############################################################################
# ControlPanel/ApproveResources.pm.pl -> ApproveResources module              #
###############################################################################
# DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING!                         #
###############################################################################
package CP::ApproveResources;

BEGIN { require "System.pm.pl"; import System qw($SYSTEM); }
BEGIN { require "General.pm.pl"; import General qw($GENERAL); }
require "Error.pm.pl";
require "Standard.pm.pl";
require "Authenticate.pm.pl";
require "StaticPages.pm.pl";
require "Mail.pm.pl";

use strict;

require "ControlPanel/Output/ApproveResources.pm.pl";

sub new {
  my ($class) = @_;
  my $self    = {};
  return bless($self, $class);
}

sub DESTROY { }

###############################################################################
# show subroutine
sub show {
  my $self = shift;
  my %in = (DB => undef, @_);

  #----------------------------------------------------------------------#
  # Authenticating...                                                    #
  
  &Authenticate::CP(DB => $in{'DB'}, ACTION => "RESOURCES_APPROVE");

  #----------------------------------------------------------------------#
  # Checking fields...                                                   #

  my @RID = $SL::CGI->param('RID');

  if (scalar(@RID) < 1) {
    &Error::Error("CP", MESSAGE => "You didn't specify any Resource IDs (RID)");
  }

  #----------------------------------------------------------------------#
  # Getting data...                                                      #

  my ($Resources, $ResourcesIndex) = $in{'DB'}->Query(
    TABLE   => "Resources",
    WHERE   => {
      ID  => \@RID
    },
    MATCH   => "ANY",
    SORT    => "CREATE_SECOND",
    BY      => "Z-A"
  );

  &Authenticate::CheckPermission(ACTION => "RESOURCES_APPROVE", CATEGORIES => [&Standard::MapArray("\${CATEGORY}", $Resources)]);

  my @FlaggedResources = grep { $_->{'FLAGS'} =~ /DELETED/ } @{$Resources};
  
  my %INPUT;
  
  $INPUT{'RESOURCES'}         = $Resources;
  $INPUT{'FLAGGED_RESOURCES'} = \@FlaggedResources;

  #----------------------------------------------------------------------#
  # Printing page...                                                     #

  my $Skin = Skin::CP::ApproveResources->new();

  &Standard::PrintHTMLHeader();
  print $Skin->show(input => \%INPUT);
  
  return 1;
}

###############################################################################
# do subroutine
sub do {
  my $self = shift;
  my %in = (DB => undef, @_);

  #----------------------------------------------------------------------#
  # Authenticating...                                                    #

  &Authenticate::CP(DB => $in{'DB'}, ACTION => "RESOURCES_APPROVE");

  #----------------------------------------------------------------------#
  # Checking fields...                                                   #

  my @RID = $SL::CGI->param('RID');

  if (scalar(@RID) < 1) {
    &Error::Error("CP", MESSAGE => "You didn't specify any Resource IDs (RID)");
  }

  #----------------------------------------------------------------------#
  # Getting data...                                                      #

  my ($Resources, $ResourcesIndex) = $in{'DB'}->Query(
    TABLE   => "Resources",
    WHERE   => {
      ID  => \@RID
    },
    MATCH   => "ANY",
    SORT    => "CREATE_SECOND",
    BY      => "Z-A"
  );

  my @Categories = &Standard::MapArray("\${CATEGORY}", $Resources);

  &Authenticate::CheckPermission(ACTION => "RESOURCES_APPROVE", CATEGORIES => \@Categories);

  my ($Categories, $CategoriesIndex) = $in{'DB'}->Query(
    TABLE   => "Categories",
    WHERE   => {
      ID  => \@Categories
    },
    MATCH   => "ANY"
  );

  #----------------------------------------------------------------------#
  # Updating data...                                                     #

  my $StaticPages = StaticPages->new(DB => $in{'DB'});
  my $Skin        = Skin::CP::ApproveResources->new();
  my $Mail        = Mail->new();

  foreach my $resource (@{ $Resources }) {
    if ($resource->{'FLAGS'} =~ /DELETED/ && $SL::QUERY{'FORM_REMOVE'}) {
      (
        $in{'DB'}->Delete(
          TABLE   => "Resources",
          KEYS    => [$resource->{'ID'}]
        )
      ) || &Error::Error("CP", MESSAGE => "Error deleting record. $in{'DB'}->{'ERROR'}");

      if ($resource->{'UPLOAD_FILENAME'} && -e "$SYSTEM->{'PUBLIC_PATH'}/Upload/$resource->{'UPLOAD_FILENAME'}") {
        unlink("$SYSTEM->{'PUBLIC_PATH'}/Upload/$resource->{'UPLOAD_FILENAME'}")
          || &Error::CGIError("Error deleting image upload file. $!", "$SYSTEM->{'PUBLIC_PATH'}/Upload/$resource->{'UPLOAD_FILENAME'}");
      }

      if ($resource->{'STATUS'}) {
        (
          $in{'DB'}->Update(
            TABLE   => "Categories",
            VALUES  => {
              RESOURCES => "--\${RESOURCES}"
            },
            KEY     => $resource->{'CATEGORY'}
          )
        ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
      }

      $StaticPages->Update(TYPE => "Detail", INPUT => $resource)
        || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
      $StaticPages->Remove(TYPE => "Detail", KEYS => [$resource->{'ID'}])
        || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
    } else {
      (
        $in{'DB'}->Update(
          TABLE   => "Resources",
          VALUES  => {
            STATUS  => "1",
            FLAGS   => ($resource->{'FLAGS'} =~ /DEAD_LINK/ ? "DEAD_LINK" : "")
          },
          KEY     => $resource->{'ID'}
        )
      ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
      
      unless ($resource->{'STATUS'}) {
        (
          $in{'DB'}->Update(
            TABLE   => "Categories",
            VALUES  => {
              RESOURCES => "++\${RESOURCES}"
            },
            KEY     => $resource->{'CATEGORY'}
          )
        ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
      }        

      $StaticPages->Update(TYPE => "Detail", INPUT => $resource)
        || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
    }

    if ($SL::QUERY{'FORM_EMAIL'}) {
      my %Message = $Skin->email(
        input => {
          "RESOURCE"  => $resource,
          "CATEGORY"  => $Categories->[$CategoriesIndex->{$resource->{'CATEGORY'}}]
        }
      );
      $Mail->Send(%Message) || &Error::Error("CP", MESSAGE => "Error sending email to user. $Mail->{'ERROR'}");
    }
  }

  my %INPUT;
  
  $INPUT{'RESOURCES'} = $Resources;
  
  #----------------------------------------------------------------------#
  # Printing page...                                                     #

  &Standard::PrintHTMLHeader();
  print $Skin->do(input => \%INPUT);
  
  return 1;
}

1;